const app = getApp();
const api = require('../../utils/api');
const Env = require('../../config/env');

let timer = ''; //定时器
let countdown = 10; //定时器时间

Page({
	data: {
        navTitle: '注册会员', //顶部导航显示的文字
        loginTipsText: '欢迎来到八桂小铺', //欢迎or提示语
        loginBtnText: '注册会员', //登录按钮显示的文字

        agree: false, //是否阅读&同意协议

        isBindUser: false, //是否第三方跳转过来绑定信息
        bindUser: '', //第三方跳转过来的用户信息

        showAgreement: false,
        showSubmit: false,
        countdown: 10,
	},

	onLoad(options) {
        // 授权手机号
        if(options.dir == 1) {
            this.setData({
                loginTipsText: '您还未授权手机号',
                loginBtnText: '授权手机号',
                navTitle: '授权手机号',
            });
            wx.setNavigationBarTitle({
                title: '授权手机号'
            });
        }
        // 登录过期，自动重新登录
        if(!app.globalData.isCanAutoLogin) {
            this.setData({
                loginBtnText: '立即登录',
                navTitle: '会员登录',
            });
            wx.setNavigationBarTitle({
                title: '会员登录'
            });
        }
        // 第三方跳转过来
        if(wx.getStorageSync('login')) {
            let data = wx.getStorageSync('login');
            this.setData({
                bindUser: data,
                isBindUser: data.phone ? true : false,
            });
        }
    },
    onShow() {
        if(!app.globalData.isCanAutoLogin) {
            this.autoLogin();
        }
    },
    goBack() {
        app.goBack();
    },

    autoLogin() { //自动登录
        wx.showLoading({
            title: '登录中...',
        });
        api.autoLogin()
            .then(res => {
                wx.setStorageSync('token', res.sessionId);
                wx.setStorageSync('userinfo', res);
                app.globalData.userInfo = res;

                if(res.phone) {
                    wx.showToast({
                        title: '登录成功！',
                        icon: 'success'
                    });

                    app.globalData.isCanAutoLogin = true;
                    setTimeout(() => {
                        wx.navigateBack(-1);
                    }, 1200);
                } else {
                    wx.showToast({
                        title: '请先授权手机号！',
                        icon: ''
                    });
                }
            })
    },

    agree() { //点击协议按钮或者协议链接
        if(!this.data.agree && !this.data.showAgreement) {
            this.setData({
                showAgreement: true
            });
            this.startCountdown();
        } else if(!this.data.agree && this.data.showAgreement) {
            this.setData({
                agree: true
            });
            this.closeAgreement();
        } else if(this.data.agree) {
            this.setData({
                showAgreement: true
            });
        }
    },
    startCountdown() {
        timer = setInterval(() => {
            if(countdown == 0) {
                this.setData({
                    showSubmit: true,
                });
                clearInterval(timer);
                countdown = 10;
            } else {
                countdown--;
                this.setData({
                    countdown: countdown
                })
            }
        }, 1000);
    },
    checkAgree() { //检查是否阅读协议
        wx.showToast({
            title: '请先阅读并同意注册协议！',
            icon: 'none'
        });
    },
    closeAgreement() {
        this.setData({
            showAgreement: false,
            showSubmit: false,
            countdown: 10,
        });
        clearInterval(timer);
        countdown = 10;
    },

    regPhoneNumber(e) { //获取手机授权
        let params = {
            appId: Env.appId,
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv,
        }
        api.post('/user/register/phone', params)
            .then(() => {
                wx.showToast({
                    title: '授权成功！',
                    icon: 'success'
                });
                if(this.data.bindUser !== '') {
                    wx.removeStorageSync('login'); //清除缓存
                }
                app.globalData.isCanAutoLogin = true;

                setTimeout(() => {
                    this.getUserInfo();
                }, 800);
            })
    },
    bindUser() { //绑定第三方小程序
        api.post(`/user/bind/third/miniapp?code=${this.data.bindUser.code}&phone=${this.data.bindUser.phone}`)
            .then(() => {
                wx.showToast({
                    title: '会员注册成功！',
                    icon: 'success'
                });

                wx.removeStorageSync('login'); //清除缓存
                app.globalData.isCanAutoLogin = true;

                setTimeout(() => {
                    this.getUserInfo();
                }, 800);
            })
    },
    getUserInfo() { //刷新用户信息
        api.post('/user/info')
            .then(res => {
                app.globalData.userInfo = res;
                wx.setStorageSync('userinfo', res);
                setTimeout(() => {
                    wx.navigateBack(-1);
                }, 500);
            })
    }
})